//
//  ProjectListControllerViewController.swift
//  mggz
//
//  Created by Apple on 2018/5/16.
//  Copyright © 2018年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import MJRefresh
import SVProgressHUD
import RxCocoa
import RxSwift

class ProjectListControllerViewController: UIViewController {
    @IBOutlet weak var tableview: UITableView!
    
    var selectarray:[String] = [String]()
    
    var datavariable:PublishSubject<[ProjectItem]> = PublishSubject()
    var dataArray:[ProjectItem] = [ProjectItem]()
    var SupplyBaseId:String?
    
    lazy var alert:UIAlertController = {
        var view = UIAlertController(title: "提示", message: "确定添加到该项目吗？", preferredStyle: .alert)
        
        view.addAction(UIAlertAction(title: "确定", style: .default, handler: { (action) in
            print("确定")
            self.submitAdd()
        }))
        view.addAction(UIAlertAction(title: "取消", style: .cancel, handler: { (action) in
            print("取消")
        }))
        return view
    }()
    
    var page = 1
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationItem.title = "选择要加入的项目"
        self.datavariable.asObservable().bind(to: self.tableview.rx.items){
            (_,row,element) in
            var index = IndexPath(row: row, section: 0)
            var cell = self.tableview.dequeueReusableCell(withIdentifier: "cell", for: IndexPath(row: row, section: 0)) as? ProjectItemCell
            cell?.data = element
            cell?.selectionStyle = .gray
            return cell!
        }
        //SVProgressHUD.setDefaultMaskType(.clear)
        //SVProgressHUD.show(withStatus: "正在加载中...")
        QWTextWithStatusHud("正在加载中...", target: self.view)
        let tableHead = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction:#selector(refresh))
        let tableFoot = MJRefreshBackNormalFooter(refreshingTarget: self, refreshingAction: #selector(loadmore))
        tableHead?.stateLabel.isHidden = true
        tableFoot?.stateLabel.isHidden = true
        self.tableview.mj_header = tableHead
        self.tableview.mj_footer = tableFoot
        self.tableview.tableFooterView = UIView(frame: CGRect.zero)
        self.tableview.estimatedRowHeight = 40
        self.tableview.register(UINib(nibName: "ProjectItemCell", bundle: nil), forCellReuseIdentifier: "cell")
        self.tableview.rx.itemSelected.map{ indexPath in
            return (indexPath,self.dataArray[indexPath.row])
            }.subscribe { (event) in
                //print("\(event.0)")
                self.SupplyBaseId = event.element?.1.MarketSupplyBaseID ?? ""
                self.tableview.deselectRow(at: (event.element?.0)!, animated: true)
                print("\(event.element?.0)")
                self.present(self.alert, animated: true, completion: nil)
        }
     //   WWProgressHUD.showWithStatus("正在加载中...")
        
        self.getDataList()
    }
    
    @objc func refresh(){
        self.page = 1
        self.getDataList()
    }
    
    @objc func loadmore(){
        self.page += 1
        self.getDataList()
    }
    
    func submitAdd(){
        QWTextWithStatusHud("正在处理...", target: self.view)
        var params:[String:Any] = ["SupplyBaseId":self.SupplyBaseId ?? "","DataItemList":self.selectarray]
        MNetHttp.sharedInstance.postSingle(API_CALL_METHOD, method: .ADDTOPROJECT, params: &params, type: AddToProject.self, success: { (bean,_) in
            QWHudDiss(self.view)
            guard var data = bean as? AddToProject else{
                return
            }
            if data.State == "OK"{
                QWTextonlyHud("添加成功", target: self.view)
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.6, execute: {
                    let vc = self.navigationController?.viewControllers[(self.navigationController?.viewControllers.count)!-2] as? WorkerOnJobViewController
                    
                    vc?.isRefresh = true
                    
                    self.navigationController?.popViewController(animated: true)
                })
            }else{
                QWTextonlyHud("添加成功", target: self.view)
            }
        }) { (error) in
            QWHudDiss(self.view)
            switch error{
            case .DATAERROR:
                QWTextonlyHud("数据异常", target: self.view)
                break
            case .DATAFAIL:
                QWTextonlyHud("数据异常", target: self.view)
                break
            case .HTTPERROR:
                QWTextonlyHud("网络异常", target: self.view)
                break
            case .StateFail(let data):
                guard let t = data as? String else{
                    guard let dic = data as? Dictionary<String, Any> else{
                        QWTextonlyHud("数据异常", target: self.view)
                        return
                    }
                    QWTextonlyHud("\(dic["Msg"] as? String ?? "")", target: self.view)
                    return
                }
                QWTextonlyHud("\(t)", target: self.view)
                break
            }
            
        }
    }
    
    func getDataList(){
        var params:[String:Any] = ["pageIndex":"\(page)","pageSize":PageSize,"IsShowFinish":"false"]
        
        MNetHttp.sharedInstance.postSingle(API_CALL_METHOD, method: .PROJECTLIST, params: &params, type: ProjectListModel.self, success: { (bean,_) in
            
            guard let data = bean as? ProjectListModel else{
                return
            }
            QWHudDiss(self.view)
            
            if self.page == 1{
                self.dataArray.removeAll()
                self.tableview.mj_header.endRefreshing()
                self.tableview.mj_footer.endRefreshing()
            }
            if self.page == 1 && (data.Result?.Items == nil || data.Result?.Items?.count == 0){
                
            }else if (data.Result?.Items == nil || (data.Result?.Items?.count ?? 0) < PageSize){
                self.tableview.mj_footer.endRefreshingWithNoMoreData()
            }else{
                self.tableview.mj_footer.endRefreshing()
            }
            self.dataArray.append(contentsOf: data.Result?.Items ?? [ProjectItem]())
            self.datavariable.onNext(self.dataArray)
            
        }) { (error) in
            QWTextWithStatusHud("数据异常", target: self.view)
        }
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
